<?php
/**
 * Created by PhpStorm.
 * User: 墨鱼行
 * Signature: 好好学习，天天向上
 * Date: 19-3-8
 * Time: 下午4:32
 */

namespace app\api\service;

use app\api\model\Product;
use think\Db;;
use think\Exception;
use think\facade\Log;
use app\api\model\Order as OrderModel;
use app\api\service\Order as OrderService;

include ($_SERVER['DOCUMENT_ROOT'] . "/../extend/WxPay/WxPay.Api.php");

class WxNotify extends \WxPayNotify
{
    //<xml>
    //<appid><![CDATA[wx2421b1c4370ec43b]]></appid>
    //<attach><![CDATA[支付测试]]></attach>
    //<bank_type><![CDATA[CFT]]></bank_type>
    //<fee_type><![CDATA[CNY]]></fee_type>
    //<is_subscribe><![CDATA[Y]]></is_subscribe>
    //<mch_id><![CDATA[10000100]]></mch_id>
    //<nonce_str><![CDATA[5d2b6c2a8db53831f7eda20af46e531c]]></nonce_str>
    //<openid><![CDATA[oUpF8uMEb4qRXf22hE3X68TekukE]]></openid>
    //<out_trade_no><![CDATA[1409811653]]></out_trade_no>
    //<result_code><![CDATA[SUCCESS]]></result_code>
    //<return_code><![CDATA[SUCCESS]]></return_code>
    //<sign><![CDATA[B552ED6B279343CB493C5DD0D78AB241]]></sign>
    //<sub_mch_id><![CDATA[10000100]]></sub_mch_id>
    //<time_end><![CDATA[20140903131540]]></time_end>
    //<total_fee>1</total_fee>
    //<coupon_fee><![CDATA[10]]></coupon_fee>
    //<coupon_count><![CDATA[1]]></coupon_count>
    //<coupon_type><![CDATA[CASH]]></coupon_type>
    //<coupon_id><![CDATA[10000]]></coupon_id>
    //<coupon_fee><![CDATA[100]]></coupon_fee>
    //<trade_type><![CDATA[JSAPI]]></trade_type>
    //<transaction_id><![CDATA[1004400740201409030005092168]]></transaction_id>
    //</xml>
    public function NotifyProcess ($objData, $config, &$msg)
    {
        if ($objData['result_code'] == 'SUCCESS')
        {
            try
            {
                Db::startTrans();
                $orderNo = $objData['out_trade_no'];
                $orderInfo = OrderModel::where('order_no', '=', $orderNo)
                    ->find();

                // 检查订单是否存在 && 订单状态是否未支付
                if (!empty($orderInfo) && $orderInfo->status == OrderService::UNPAID)
                {
                    // 检查库存是否充足
                    $orderService = new OrderService();
                    $stockStatus = $orderService->getOrderStatusByOrderId($orderInfo->order_id);

                    if ($stockStatus['pass'])
                    {
                        // 减掉库存
                        $this->reduceStock($stockStatus);
                        // 修改支付状态
                        $this->updateOrderStatus($orderInfo->order_id, true);
                    }
                    else
                    {
                        // 修改支付状态
                        $this->updateOrderStatus($orderInfo->order_id, false);
                    }
                }
                Db::commit();
                return true;
            }
            catch (Exception $e)
            {
                Db::rollback();
                Log::error($e);
                return false;
            }
        }
        else
        {
            return true;
        }
    }

    /**
     * 更新支付状态
     * @param $orderId
     * @param $isSuccess
     */
    private function updateOrderStatus($orderId, $isSuccess)
    {
        $status = $isSuccess ? OrderService::ISPAID : OrderService::PAY_BUT_OUT_OF;
        OrderModel::where('order_id', '=', $orderId)
            ->update(['status' => $status]);
    }

    /**
     * 减少库存数量
     * @param $stockStatus
     * @throws Exception
     */
    private function reduceStock($stockStatus)
    {
        foreach ($stockStatus['pStatusArray'] as $item)
        {
            Product::where('id', '=', $item['id'])
                ->setDec('stock', $item['count']);
        }
    }
}